import Konva from '@/static/js/konav.js';
import { IStage } from '../../types/render';
import { ILayerAttrs } from '../../types/editor/layer';
import { IRectAttrs } from '../../types/editor/rect';
import { IGroupAttrs } from '../../types/editor/group';
import { IPathAttrs } from '../../types/editor/path';
import { ITextAttrs } from '../../types/editor/text';

export const kName = 'konva';

export const Stage = (data: IStage) => {
    return new Promise((resolve) => {
        resolve(new Konva.Stage({
            container: data.container,
            width: data.width,
            height: data.height,
        }));
    });
};

export const Layer = (data: ILayerAttrs) => {
    const layerData: ILayerAttrs = {
        x: data.x,
        y: data.y,
        opacity: data.opacity || 1,
        scale: data.scale || { x: 1, y: 1 },
        rotation: data.rotation || 0,
    };
    data.id && (layerData.id = data.id);
    return new Promise((resolve) => {
        resolve(new Konva.Layer(layerData));
    });
};

export const Rect = (data: IRectAttrs) => {
    return new Promise((resolve) => {
        resolve(new Konva.Rect(data));
    });
};

export const Group = (data: IGroupAttrs) => {
    const rectData: IGroupAttrs = {
        x: data.x,
        y: data.y,
        width: data.width,
        height: data.height,
    };
    data.id && (rectData.id = data.id);
    data.opacity && (rectData.opacity = data.opacity);
    data.rotation && (rectData.rotation = data.rotation);
    return new Promise((resolve) => {
        resolve(new Konva.Group(rectData));
    });
};

export const Path = (data: IPathAttrs) => {
    const rectData: IPathAttrs = {
        data: data.data,
        stroke: data.stroke,
        strokeWidth: data.strokeWidth,
    };
    data.id && (rectData.id = data.id);
    return new Promise((resolve) => {
        resolve(new Konva.Path(rectData));
    });
};

export const Text = (data: ITextAttrs) => {
    const rectData: ITextAttrs = {
        x: data.x,
        y: data.y,
        width: data.width,
        height: data.height,
        fill: data.fill,
        text: data.text,
        fontSize: data.fontSize,
        lineHeight: data.lineHeight || data.fontSize,
        strokeWidth: data.strokeWidth || 1,
    };
    data.id && (rectData.id = data.id);
    'opacity' in data && (rectData.opacity = data.opacity);
    return new Promise((resolve) => {
        resolve(new Konva.Text(rectData));
    });
};
